package com.damai.action.json;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.entities.Customer;
import com.citywithincity.api.utils.ApiUtil;
import com.citywithincity.cache.CacheUtil;
import com.citywithincity.utils.JsonUtil;
import com.damai.action.NoAccessTokenError;
import com.damai.action.NotLoginError;
import com.damai.annotation.UploadFile;
import com.damai.annotation.UploadFileList;
import com.damai.error.ApiError;

public class FileParamParser implements IGetJson {
	public static class ApiUploadFileInfo {

		public String name;
		public String ext;
		public int type;
	}

	private ApiUploadFileInfo[] infos;
	
	

	public FileParamParser(UploadFileList uploadFileList) {
		infos = new ApiUploadFileInfo[uploadFileList.value().length];
		int index = 0;
		for (UploadFile file : uploadFileList.value()) {
			ApiUploadFileInfo info = new ApiUploadFileInfo();
			infos[index++] =info;
			info.name = file.name();
			info.ext = file.ext();
			info.type = file.type();
		}
	}

	@Override
	public Map<String, Object> getJson(HttpServletRequest request) throws IOException {
		InputStream inputStream = request.getInputStream();
		int contentLength = request.getContentLength();
		String attach = request.getHeader("attach");
		String[] files = attach.split(",");
		if(files.length!=infos.length){
			throw new ApiError("文件数量不符合");
		}
		//文件大小
		int[] lengths = new int[files.length];
		int totalLen = 0;
		int index = 0;
		for (String nlen : files) {
			int len = Integer.parseInt(nlen);
			lengths[index++]=len;
			totalLen+=len;
		}
		//jsonLen
		int jsonLen = contentLength - totalLen;
		if(jsonLen<=0){
			throw new ApiError("没有数据");
		}
		byte[] bytes = new byte[jsonLen];
		inputStream.read(bytes);
		Customer customer = (Customer) request.getAttribute("customer");
		if(customer == null){
			String token = request.getHeader("token");
			if(token == null){
				throw new NoAccessTokenError();
			}
			customer = CacheUtil.get(token);
			if(customer == null){
				throw new NoAccessTokenError();
			}
			
		}
		if(customer.getId()==null){
			throw new NotLoginError();
		}
		Map<String, Object> json = read(bytes,customer);
		json.put("customer",customer);
		request.setAttribute("time", json.get("time"));
		request.setAttribute("customer", customer);
		json.put(ApiUtil.fileReader, new ApiFileReader(lengths,infos,contentLength,inputStream));
		return json;
	}

	protected Map<String, Object> read(byte[] bytes, Customer customer) throws IOException {
		return JsonUtil.read(bytes);
	}

}
